package com.luocj.looook.fragment;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.luocj.looook.R;
import com.luocj.looook.URL;
import com.luocj.looook.activity.WebViewActivity;
import com.luocj.looook.adapter.BaseRecyclerAdapter;
import com.luocj.looook.adapter.SmartViewHolder;
import com.luocj.looook.base.BaseFragment;
import com.luocj.looook.model.NewsModel;
import com.luocj.looook.utils.Constant;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luocj515 on 2017/11/21.
 * 项目名称：LooooK
 * 类描述：
 * 创建人：hasee
 * 创建时间：2017/11/21 14:24
 * 修改备注：
 */

public class NewsFragment extends BaseFragment {

    private static final String TAG = NewsFragment.class.getSimpleName();
    private ArrayList<NewsModel.NewslistBean> news = new ArrayList<>();
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recyclerView;
    private BaseRecyclerAdapter<NewsModel.NewslistBean> newsAdapter;
    private int pageSize = 30;//每次五个
    private boolean isFirstIn = true;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        smartRefreshLayout = mContentView.findViewById(R.id.swiperefeshlayout);
        recyclerView = mContentView.findViewById(R.id.recyclerview_news);
        LinearLayoutManager layout = new LinearLayoutManager(mContentView.getContext(), LinearLayoutManager.VERTICAL, false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContentView.getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);

        recyclerView.setAdapter(newsAdapter = new BaseRecyclerAdapter<NewsModel.NewslistBean>(news, R.layout.item_news, null) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, final NewsModel.NewslistBean model, final int position) {
                ImageView newsPic = holder.itemView.findViewById(R.id.iv_newspic);
                Glide.with(mContentView.getContext())
                        .load(model.getPicUrl())
                        .centerCrop()
                        .into(newsPic);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(mContentView.getContext(), position + "", Toast.LENGTH_SHORT).show();
                        Intent webViewIntent = new Intent(mContentView.getContext(), WebViewActivity.class);
                        webViewIntent.putExtra(WebViewActivity.DATA_URL, model.getUrl());
                        startActivity(webViewIntent);
                    }
                });
            }
        });

        if (isFirstIn) {
            isFirstIn = false;
            smartRefreshLayout.autoRefresh();
        }
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (news.size() != 0) {
                            news.clear();
                        }
                        refreshData();
                    }
                }, 2000);
            }
        });

        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMore();
                    }
                }, 2000);
            }
        });
    }

    private void loadMore() {
        OkGo.<String>get(URL.BASE_URL_WXNEWS)
                .params("key", "861a794733dd2b057e415d822bef9586")
                .params("num", pageSize)
                .tag(NewsFragment.class.getSimpleName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        NewsModel newsModel = JSONObject.parseObject(response.body().toString(), NewsModel.class);
                        List<NewsModel.NewslistBean> newslist = newsModel.getNewslist();
                        newsAdapter.loadmore(newslist);
                        smartRefreshLayout.finishLoadmore();
                        if (newsAdapter.getItemCount() >= Constant.MAX_SIZE) {
                            smartRefreshLayout.setLoadmoreFinished(true);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i(TAG, "onError: " + response.body().toString());
                    }

                });

    }

    private void refreshData() {
        OkGo.<String>get(URL.BASE_URL_WXNEWS)
                .params("key", "861a794733dd2b057e415d822bef9586")
                .params("num", pageSize)
                .tag(NewsFragment.class.getSimpleName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        NewsModel newsModel = JSONObject.parseObject(response.body().toString(), NewsModel.class);
                        List<NewsModel.NewslistBean> newslist = newsModel.getNewslist();
                        for (int i = 0; i < newslist.size(); i++) {
                            news.add(newslist.get(i));
                        }
                        newsAdapter.refresh(news);
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.setLoadmoreFinished(false);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i(TAG, "onError: " + response.toString());
                    }
                });
    }

    @Override
    protected void initData() {

    }
}
